const express = require('express')
const router = express.Router()
module.exports = router;

router.use(
    express.json(),
    express.urlencoded({extended:true}), 
)

const mysql = require('../db/mysql');
const {formatData} = require('../utils')

// 2.接口服务器（RESTful规范）
const userRouter = require('./user')

//  /api/user
router.use('/user',userRouter)

// @注册
// POST /api/reg
router.post('/reg', (req, res) => {
    const { username, password } = req.body;
    let sql = `insert into user(username,password) values('${username}','${password}')`
    mysql.query(sql,(result)=>{
        if(result.insertId){
            res.send(formatData.success())
        }else{
            res.send(formatData({code:400}))
        }
    })
})

// @登录
// POST /api/login才进入以下路由
router.post('/login', (req, res) => {
    const {username,password} = req.body;
    let sql = `select * from user where username='${username}' and password='${password}'`
    mysql.query(sql,(result)=>{
        if(result.length>0){
            res.send(formatData.success(result[0]))
        }else{
            res.send(formatData.fail())
        }
    })
})

//view
router.get('/view',(req,res)=>{
    // console.log('cookie',req.cookies)
    const userAgent = req.get('User-Agent')
    if(userAgent.indexOf('Windows')>=0){
        res.send('你使用PC浏览器')
    }else{
        res.send('你使用的是移动端')
    }
})








